const express = require('express')
const userInfo = express.Router()
const db = require('../db')


// 使用 joi 做表单校验
const Joi = require("joi")
// 定义表单验证规则
const user_schema = Joi.object(
    {
        id: Joi.number().integer().required().error(new Error("id不存在")),
        nickname: Joi.string().min(1).max(20).error(new Error("昵称不规范")),
        email: Joi.string().email().error(new Error("邮箱不规范")),
        user_pic: Joi.string().error(new Error("请上传头像的图片地址")),
    }
)
// const info = {username: 'admin', password:"123456"}
// schema.validateAsync(info);

// 引进 创建表单校验方法
const { validation } = require("../utils")
// 引进加密 bcryptjs
const bcryptjs = require('bcryptjs')


// 获取用户信息
userInfo.get('/userInfo', (req, res) => {
    const id = req.query.id || req.auth.userInfo.id
    if (!id) return res.cc('用户id不能为空')
    db.query('select id,username,nickname,email,user_pic from ev_users where id = ?', id, (err, result) => {
        if (err) return res.cc(err)
        res.send({ code: 200, msg: '成功', data: result[0] })
    })
})

// 更新用户信息
userInfo.post('/userInfo', validation(user_schema), (req, res) => {
    const { id, nickname, email, user_pic } = req.body
    db.query('update ev_users set ? where id = ?', [{ nickname, email, user_pic }, id], (err, result) => {
        if (err) return res.cc(err)
        res.send({ code: 200, msg: '成功', data: req.body })
    })
})

// 修改密码
const password_schema = Joi.object(
    {
        oldpwd: Joi.string().required().regex(/^\w{6,16}$/).error(new Error("密码不规范")),
        newpwd: Joi.not(Joi.ref('oldpwd')).concat(Joi.string().required().regex(/^\w{6,16}$/).error(new Error("新旧密码不能一样")))
    }
)
userInfo.post('/password', validation(password_schema), (req, res) => {
    const id = req.auth.userInfo.id
    db.query('SELECT password FROM ev_users WHERE id = ?', id, (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 1) return res.cc('用户不存在!')
        // 密码对比
        if (!bcryptjs.compareSync(req.body.oldpwd, result[0].password)) {
            return res.cc('旧密码不正确!')
        } else {
            // 旧密码匹配成功，修改新密码到数据库
            const newpwd = bcryptjs.hashSync(req.body.newpwd)
            db.query('update ev_users set password = ? where id = ? ', [newpwd, id], (err, result) => {
                if (err) return res.cc(err)
                if (result.affectedRows !== 1) {
                    return res.cc('失败，请稍后再试')
                }
                res.send({ code: 200, msg: '成功', data: '' })
            })
        }
    })
})

// commonjs 导出模块
module.exports = userInfo